package com.zqr.lock;

import java.util.concurrent.locks.ReentrantLock;

//ReentrantLock可重入案例
public class ReentrantLockDemo2 {
    private static int count;
    private static ReentrantLock lock = new ReentrantLock();

    public static void incr(){
        lock.lock();
        count++;
        System.out.println(Thread.currentThread().getName() + "执行了count++");
        //因为可重入，所以单个线程在这里还能继续执行reduce方法
        reduce();
        lock.unlock();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void reduce(){
        lock.lock();
        count--;
        System.out.println(Thread.currentThread().getName() + "执行了count--");
        lock.unlock();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(ReentrantLockDemo2::incr,"thread" + i).start();
        }
    }
}
